/*
 * CRtpMediaChannel.h
 *
 *  Created on: 2017年4月6日
 *      Author: chuanjiang.zh
 */

#ifndef CRTPMEDIACHANNEL_H_
#define CRTPMEDIACHANNEL_H_

#include "RtpMediaChannel.h"
#include "MediaSourceT.h"
#include "TThread.h"
#include "TCriticalSection.h"
#include "RtpPackager.h"
#include "RtpPacketPtr.h"
#include "MediaPacketQueue.h"


class JRTPSession;

namespace av
{

typedef std::shared_ptr< RtpPackager >		RtpPackagerPtr;


class CRtpMediaChannel: public MediaSourceT<RtpMediaChannel>, public comn::Thread, public RtpPackagerSink
{
public:
	CRtpMediaChannel();
	virtual ~CRtpMediaChannel();

	virtual int open(const std::string& url, const std::string& params);
	virtual void close();
	virtual bool isOpen();

	virtual std::string getUrl();

	virtual int startStream();

	virtual int pauseStream();

	virtual void stopStream();

	virtual int getState();

	virtual int forceKeyFrame();


    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(MediaPacketPtr& pkt);

    virtual void onMediaEvent(int event);


	virtual std::string getName();

	virtual NetAddress getLocalAddr();

	virtual void setMaxPacetSize(size_t size);

    virtual void setPayload(uint8_t payload);

    virtual uint8_t getPayload();

    virtual void setMediaType(int mediaType);

    virtual int getMediaType();


    virtual void setPeerAddr(const std::string& ip, int port);

	virtual NetAddress getPeerAddr();

	virtual void setPeerMedium(int payload, int codec, int clockrate, const std::string& sprop);

	void enableRecv(bool enabled);

protected:
    virtual int run();
    virtual void doStop();

    virtual void onSlicePacket(const RtpPacket& pkt);

protected:
    bool openRtpSession(uint16_t port);
	void closeRtpSession();

	void clearCache();

	void sendPacket(MediaPacketPtr& pkt);

	void sendPacket(const RtpPacket& packet);

	bool poll(int ms);

	bool readAndHandle();

	void onRtpPacket(jrtplib::RTPPacket* pPacket);

	void addDestination(const std::string& ip, int port);
	void removeDestination(const std::string& ip, int port);

	void timedwait(int ms);

protected:
    NetAddress	m_localAddr;
	size_t m_maxPktSize;
    uint8_t m_payload;
    int		m_mediaType;

    NetAddress	m_peerAddr;

    typedef std::shared_ptr< JRTPSession >  JRTPSessionPtr;

    JRTPSessionPtr  	m_session;
    MediaPacketQueue    m_pktQueue;
    RtpPackagerPtr		m_packager;

    int64_t 	m_packetCount;
    uint32_t    m_lastTime;

	bool	m_recvEnabled;

};


} /* namespace av */

#endif /* CRTPMEDIACHANNEL_H_ */
